<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>家庭记账本 - 用户管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background-color: #f8f9fa;
            padding: 20px;
        }
        .main-content {
            padding: 20px;
        }
        .user-status-active {
            color: #198754;
        }
        .user-status-inactive {
            color: #dc3545;
        }
        .user-role-admin {
            color: #0d6efd;
        }
    </style>
    <script>
        // 兜底：如果当前URL为/users/edit，自动跳转回用户管理页，避免空白
        if (window.location.pathname.endsWith('/users/edit')) {
            window.location.href = '${pageContext.request.contextPath}/users';
        }
    </script>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 sidebar">
                <h3 class="mb-4">家庭记账本</h3>
                <div class="list-group">
                    <a href="profile" class="list-group-item list-group-item-action">个人中心</a>
                    <a href="dashboard" class="list-group-item list-group-item-action">总账单</a>
                    <a href="transactions" class="list-group-item list-group-item-action">收支记录</a>
                    <c:if test="${fn:toUpperCase(sessionScope.user.role) == 'GOD' || fn:toUpperCase(sessionScope.user.role) == 'ADMIN'}">
                        <a href="users" class="list-group-item list-group-item-action active">用户管理</a>
                    </c:if>
                    <a href="logout" class="list-group-item list-group-item-action text-danger">退出登录</a>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-10 main-content">
                <!-- 用户信息展示 -->
                <div class="alert alert-info mb-3" style="padding: 8px 16px;">
                    当前账号：<strong>${sessionScope.user.username}</strong>，姓名：<strong>${sessionScope.user.name}</strong>，身份：
                    <strong>
                        <c:choose>
                            <c:when test="${sessionScope.user.role eq 'GOD'}">超级管理员</c:when>
                            <c:when test="${sessionScope.user.role eq 'ADMIN'}">管理员</c:when>
                            <c:otherwise>普通用户</c:otherwise>
                        </c:choose>
                    </strong>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>用户管理</h2>
                </div>
                <c:if test="${not empty error}">
                    <div class="alert alert-danger" role="alert">
                        ${error}
                    </div>
                </c:if>

                <!-- Users Table -->
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>用户名</th>
                                        <th>姓名</th>
                                        <th>邮箱</th>
                                        <th>角色</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <c:forEach var="user" items="${users}">
                                        <tr>
                                            <td>${user.username}</td>
                                            <td>${user.name}</td>
                                            <td>${user.email}</td>
                                            <td>
                                                <c:choose>
                                                    <c:when test="${fn:toUpperCase(user.role) == 'GOD'}">
                                                        <span style="color: #dc3545; font-weight: bold;">超级管理员</span>
                                                    </c:when>
                                                    <c:when test="${fn:toUpperCase(user.role) == 'ADMIN'}">
                                                        <span class="user-role-admin">管理员</span>
                                                    </c:when>
                                                    <c:otherwise>
                                                        普通用户
                                                    </c:otherwise>
                                                </c:choose>
                                            </td>
                                            <td>${user.createdAtStr}</td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-outline-primary edit-user"
                                                        data-id="${user.id}"
                                                        data-username="${user.username}"
                                                        data-name="${user.name}"
                                                        data-email="${user.email}"
                                                        data-role="${user.role}">
                                                    <i class="bi bi-pencil"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    </c:forEach>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div class="modal fade" id="editUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm" action="${pageContext.request.contextPath}/users/edit" method="post">
                        <input type="hidden" id="editUserId" name="id">
                        <div class="mb-3">
                            <label for="editUsername" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="editUsername" name="username" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="editName" class="form-label">姓名</label>
                            <input type="text" class="form-control" id="editName" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="editEmail" class="form-label">邮箱</label>
                            <input type="email" class="form-control" id="editEmail" name="email" required>
                        </div>
                        <div class="mb-3">
                            <label for="editPassword" class="form-label">新密码</label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="editPassword" name="password" placeholder="不修改请留空">
                                <button class="btn btn-outline-secondary" type="button" id="toggleEditPassword" tabindex="-1">
                                    <i class="bi bi-eye" id="editPasswordIcon"></i>
                                </button>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="editRole" class="form-label">用户角色</label>
                            <select class="form-select" id="editRole" name="role" required>
                                <option value="USER">普通用户</option>
                                <option value="ADMIN">管理员</option>
                                <option value="GOD">超级管理员</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" form="editUserForm" class="btn btn-primary">保存</button>
                    <form id="deleteUserFormInEdit" action="${pageContext.request.contextPath}/users/delete" method="post" style="display:none;">
                        <input type="hidden" id="deleteUserIdInEdit" name="id">
                    </form>
                    <button type="button" class="btn btn-danger" id="deleteUserBtnInEdit">删除用户</button>
                    <span id="deleteCountdownInEdit" style="margin-left:10px;color:#dc3545;display:none;"></span>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete User Modal -->
    <div class="modal fade" id="deleteUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p class="fw-bold text-danger">警告：该操作会删除用户及其所有数据，且不可恢复。请谨慎操作！</p>
                    <p>确定要删除用户 "<span id="deleteUsername"></span>" 吗？</p>
                    <form id="deleteUserForm" action="${pageContext.request.contextPath}/users/delete" method="post">
                        <input type="hidden" id="deleteUserId" name="id">
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" id="confirmDeleteBtn" form="deleteUserForm" class="btn btn-danger" disabled>确认 (<span id="deleteCountdown">5</span>s)</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Edit user modal
        document.querySelectorAll('.edit-user').forEach(button => {
            button.addEventListener('click', function() {
                const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
                const data = this.dataset;
                document.getElementById('editUserId').value = data.id;
                document.getElementById('editUsername').value = data.username;
                document.getElementById('editName').value = data.name;
                document.getElementById('editEmail').value = data.email;
                document.getElementById('editRole').value = data.role;
                modal.show();
            });
        });

        // Delete user modal
        let deleteTimer = null;
        document.querySelectorAll('.delete-user').forEach(button => {
            button.addEventListener('click', function() {
                const modal = new bootstrap.Modal(document.getElementById('deleteUserModal'));
                const data = this.dataset;
                document.getElementById('deleteUserId').value = data.id;
                document.getElementById('deleteUsername').textContent = data.username;
                // 5秒倒计时保护
                const confirmBtn = document.getElementById('confirmDeleteBtn');
                let seconds = 5;
                confirmBtn.disabled = true;
                confirmBtn.innerHTML = `确认 (<span id="deleteCountdown">${seconds}</span>s)`;
                if (deleteTimer) clearInterval(deleteTimer);
                deleteTimer = setInterval(() => {
                    seconds--;
                    confirmBtn.innerHTML = `确认 (<span id="deleteCountdown">${seconds}</span>s)`;
                    if (seconds <= 0) {
                        clearInterval(deleteTimer);
                        confirmBtn.disabled = false;
                        confirmBtn.textContent = '确认';
                    }
                }, 1000);
                modal.show();
            });
        });

        document.getElementById('toggleEditPassword').onclick = function() {
            var pwd = document.getElementById('editPassword');
            var icon = document.getElementById('editPasswordIcon');
            if (pwd.type === 'password') {
                pwd.type = 'text';
                icon.classList.remove('bi-eye');
                icon.classList.add('bi-eye-slash');
            } else {
                pwd.type = 'password';
                icon.classList.remove('bi-eye-slash');
                icon.classList.add('bi-eye');
            }
        };

        // 编辑弹窗内删除用户按钮逻辑（带5秒倒计时二次确认）
        let deleteTimerInEdit = null;
        document.getElementById('deleteUserBtnInEdit').onclick = function() {
            const btn = this;
            const countdownSpan = document.getElementById('deleteCountdownInEdit');
            if (btn.disabled) return;
            if (confirm('确定要删除该用户吗？此操作不可恢复！')) {
                let seconds = 5;
                btn.disabled = true;
                countdownSpan.style.display = 'inline';
                countdownSpan.textContent = `请等待 ${seconds} 秒确认...`;
                deleteTimerInEdit = setInterval(() => {
                    seconds--;
                    countdownSpan.textContent = `请等待 ${seconds} 秒确认...`;
                    if (seconds <= 0) {
                        clearInterval(deleteTimerInEdit);
                        countdownSpan.textContent = '';
                        countdownSpan.style.display = 'none';
                        btn.disabled = false;
                        if (confirm('再次确认：确定要删除该用户吗？')) {
                            var deleteId = document.getElementById('editUserId').value;
                            alert('即将删除的用户ID为：' + deleteId);
                            document.getElementById('deleteUserIdInEdit').value = deleteId;
                            document.getElementById('deleteUserFormInEdit').submit();
                        }
                    }
                }, 1000);
            }
        };
    </script>
    <c:if test="${not empty error}">
        <script>
            alert('${error}');
            // 弹窗后自动跳转回用户管理页，清除URL参数，避免多次弹窗
            window.location.href = '${pageContext.request.contextPath}/users';
        </script>
    </c:if>
</body>
</html> 